/*********************************************************************************
 *       Copyright:  (C) 2018 Wu Yujun<540726307@qq.com>
 *                   All rights reserved.
 * 
 *        Filename:  msgqueue_send.c
 *        Description:  This file  is msgqueue send program
 *                  
 *        Version:  1.0.0(2018年12月27日)
 *        Author:  Wu Yujun <540726307@qq.com>
 *       ChangeLog:  1, Release initial version on "2018年12月27日 21时58分50秒"
 *                  
 *********************************************************************************/

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define mtext_size 512

struct s_msg{ /* msgp定义的参照格式*/
        long type; /*  必须大于0,消息类型 */
        char mtext[mtext_size]; /* 消息正文，可以是其他任何类型*/           
} ;
int main(int argc ,char ** argv)
{
        key_t           key ;
        int             msgid ;
        struct s_msg    msgbuf ;

        key = ftok(".", 0x98) ; // 获取IPC关键字
        if(key == -1) 
        {
            printf("ftok() failed: %s\n", strerror(errno));
            return -1 ;
        }
        printf("ftok sucessful, and create key = %d\n", key) ;
        msgid = msgget(key, IPC_CREAT|0644) ;//创建一个新的或打开一个已经存在的消息队列
        if(msgid == -1)
        {
            printf("msgget() failed: %s\n", strerror(errno));
            return -2 ;
        }
        printf("msgget() sucessful, msgid = %d\n", msgid);
        memset(&msgbuf,0, sizeof(msgbuf) ) ;
        msgbuf.type = msgid ;
        snprintf( msgbuf.mtext, sizeof(msgbuf.mtext), "Hello msgqueue recver!")  ;
                                                                     
        if( msgsnd(msgid, &msgbuf, strlen(msgbuf.mtext), IPC_NOWAIT) == -1 ) //发送消息
        {                    
            printf("msgsnd() failed: %s\n", strerror(errno));
            msgctl(msgid, IPC_RMID, NULL) ;
            return -3 ;      
        }                    
        printf("msgqueue send '%s' to msgqueue sucessful!\n", msgbuf.mtext) ;                                                                              
        
        return  0 ;
                            

}
